<template>
  <div class="shopping-cart">

    <van-nav-bar :left-text="address.slice(0,address.indexOf('市')+1)" title="购物车" :right-text="btn ? '管理': '完成编辑'" @click-right="manage" />

    <div class="list">
      <div v-show="userCartList.length === 0">
        <van-empty description="快去添加商品吧" />
      </div>
      <div v-show="userCartList.length !== 0" class="product-list" v-for="item in userCartList" :key="item.id">
        <van-checkbox-group v-model="result" ref="checkboxGroup">
          <van-checkbox :name="item.id" checked-color="rgb(251,44,33)" />

          <div class="product-card">
            <div class="product-picture">
              <img :src="baseUrl + item.bgUrl"/>
            </div>
            <div class="product-info">
              <p class="product-name">{{item.name}}</p>
              <div class="price">
                <div class="left">
                  ￥
                  <span>{{item.price * item.count}}</span>
                </div>
                <div class="btn">
                  <input type="button" value="-" @click="reduce(item.id)" />
                  <input type="text" :value="item.count" />
                  <input type="button" value="+" @click="plus(item.id)" />
                </div>
              </div>
            </div>
          </div>
        </van-checkbox-group>
      </div>
    </div>

    <van-submit-bar :disabled="!isok" v-show="btn" :price="totalPrice" button-text="结算" @click.native="buy">
      <van-checkbox v-model="checked" @click="checkAll" checked-color="rgb(251,44,33)">全选</van-checkbox>
    </van-submit-bar>  

    <van-submit-bar v-show="!btn" button-text="删除" @click.native="del">
      <van-checkbox v-model="checked" @click="checkAll" checked-color="rgb(251,44,33)">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import { addOrder, cartList, changeCartInfo, deleteCart } from "../../apis/cartApi";
import { myAddress } from "../../apis/meApi"
export default {
  data() {
    return {
      result: [],
      checked: false,
      radio: 1,
      btn: true,
      userCartList: [],
      // totalPrice: 0,
      baseUrl:'http://10.7.162.81:15666',
      address:''
    };
  },
  
  created() {
    this.loadPage();
    this.getAddress()
  },

  watch: {
    result: {
      deep: true,
      handler(val) {
        if(val.length !== 0){
          this.checked = val.length === this.userCartList.length;
        }
      },
    },
    checked(){
      console.log('我改变了');
    }
  },

  computed:{
    totalPrice(){
      let checkProduct = []
      for(let i = 0;i < this.result.length;i++){
        this.userCartList.forEach(item => {
          if(item.id === this.result[i]){
            checkProduct.push(item)
          }
        })
      }
      let total = 0
      checkProduct.forEach(item => {
        total += item.count * item.price
      })
      return total * 100
    },
    isok(){
      return this.result.length > 0
    }
  },

  methods: {
    /** 管理、完成编辑状态切换 */
    manage() {
      this.btn = !this.btn;
    },
    /** 减商品数量 */
    reduce(id) {
      let product = this.userCartList.find((item) => item.id === id);
      if (product.count > 1) {
        product.count--;
      }
      if (product.count <= 1) {
        product.count = 1;
      }
      this.chengeInfo({
        userId: this.$store.getters["common/user"].id,
        id,
        count: product.count,
      });
    },
    /** 加商品数量 */
    plus(id) {
      let product = this.userCartList.find((item) => item.id === id);
      product.count++;
      this.chengeInfo({
        userId: this.$store.getters["common/user"].id,
        id,
        count: product.count,
      });
    },
    /** 全选 */
    checkAll() {
      if (this.checked) {
        this.result = this.userCartList.map((it) => {
          return it.id;
        });
      } else {
        this.result = [];
      }
    },
    /** 删除购物车商品 */
    del(event) {
      if (event.target.innerText === "删除") {
        console.log("删除", this.result);
        deleteCart({
          userId: this.$store.getters["common/user"].id,
          ids: this.result,
        }).then((res) => {
          console.log(res);
          this.result = []
          this.loadPage();
        });
      }
    },
    /** 商品结算 */
    buy(event) {
      if (event.target.innerText === "结算") {
        let list = []
        let time = new Date()
        if (this.address !== '' && this.result.length > 0) {
          for(let i = 0;i < this.result.length;i++){
            this.userCartList.forEach(item => {
              if(item.id === this.result[i]){
                list.push({
                  price:item.price,
                  id:item.id,
                  time:`${time.getFullYear()}-${time.getMonth()+1}-${time.getDate()}`,
                  count:item.count,
                  name:item.name,
                  detailaddress:this.address,
                  bgUrl:item.bgUrl
                })
              }
            })
          }
          console.log(list,65456465465465456);
          addOrder({userId:this.$store.getters["common/user"].id, list}).then(res => {
            console.log(res);
              if(res.code === 200){
                this.result = []
                this.loadPage();
              }
          })
        }else if (this.address === '') {
          // this.$toast('');
          this.$toast('你还没有地址哟');
        }else{
          
        }
      }
    },
    /** 修改商品信息 */
    chengeInfo(data) {
      changeCartInfo(data);
    },
    /** 获取购物车列表数据 */
    loadPage() {
      this.checked = false
      this.userCartList = []
      cartList(this.$store.getters["common/user"].id).then((resolve) => {
        if (resolve.code === 200) {
          resolve.data.forEach((item) => {
            this.userCartList.push(item);
          });
        }
      });
    },
    /** 获取用户地址 */
    getAddress(){
      myAddress(this.$store.getters["common/user"].id).then(res => {
        if(res.code === 200){
          if (res.data.length > 0) {
            this.address = res.data.splice(res.data.length-1,1)[0].address
          }else{
            this.address = ''
          }
        }
      })
    }
  },
};
</script>

<style lang="less" scoped>
.shopping-cart {
  position: relative;
  width: 100%;
  height: calc(100% - 50px);
  background-color: rgb(246, 246, 245);
  .van-nav-bar {
    font-size: 16px;
    font-weight: bold;
  }
  .list {
    height: calc(100% - 46px - 50px);
    overflow-x: hidden;
    .product-list {
      display: block;
      width: 94%;
      height: 110px;
      padding: 0 8px;
      margin: auto;
      margin-top: 6px;
      background-color: white;
      border-radius: 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .van-checkbox-group {
        display: flex;
        width: 100%;
        .van-checkbox {
          margin-right: 8px;
        }
        .product-card {
          width: 92%;
          height: 100px;
          display: flex;
          justify-content: space-between;
          .product-picture {
            width: 30%;
            img {
              width: 100%;
              height: 100%;
            }
          }
          .product-info {
            width: 66%;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            .product-name {
              height: 50%;
              margin: 0;
              font-size: 0.9rem;
              overflow: hidden;
            }
            .price {
              height: 30%;
              display: flex;
              justify-content: space-between;
              .left {
                width: 40%;
                font-size: 0.7rem;
                color: rgb(251, 44, 33);
                span {
                  font-size: 0.95rem;
                }
              }
              .btn {
                width: 46%;
                display: flex;
                > input:nth-child(odd) {
                  font-weight: bold;
                  width: 30px;
                  height: 30px;
                  border: 0 solid #000;
                  background-color: rgba(10, 10, 10, 0);
                }
                > input:nth-child(even) {
                  width: 36px;
                  height: 30px;
                  font-size: 0.8rem;
                  text-align: center;
                  border: 0 solid #000;
                  background-color: rgb(242, 242, 246);
                }
              }
            }
          }
        }
      }
    }
  }

  .van-submit-bar {
    bottom: 50px;
    .van-submit-bar__bar {
      justify-content: space-between;
    }
  }
}
</style>